const fs = require('fs')
const os = require("os");


class LogController {
    logFilePath = require('../../config/index').log.runTimeLogFilePath
    logFileName = require('../../config/index').log.runTimeLogFileName
    a = 1

    constructor() {
        // 在appendFileSync中 若不存在目标路径会自动创建 所以不需要检测
        if (!fs.existsSync(this.logFilePath)) fs.mkdirSync(this.logFilePath, {mode: 0o777})
        // if (!fs.existsSync(this.logFilePath)) fs.writeFileSync(this.logFilePath, '', {encoding: 'utf8', mode: 0o777})
    }

    /**
     * @desc 添加日志
     * @param content
     * @param time
     */
    addLog({content, time = new Date().toLocaleString()}) {
        fs.appendFileSync(this.logFilePath + '/' + this.logFileName, `${content} | ${time}` + os.EOL, {
            encoding: 'utf8',
            flag: 'a+'
        })
    }

    testArrAdd() {
        if (this.a > 10000) return console.log('已超过预定值')
        setTimeout(() => {
            fs.appendFileSync(this.logFilePath, this.a + os.EOL, {encoding: 'utf8'})
            this.a++
            this.testArrAdd(this.a)
        }, 1)
    }

    /**
     * @desc 将log数据格式化为对象数组
     * @returns {*[Object]}
     */
    formatToJSON() {
        let context = fs.readFileSync(this.logFilePath, {encoding: 'utf8'})
        let ctxArr = context.split(os.EOL)
        let target = []
        let index = 0;
        while (index < ctxArr.length) {
            let str = ctxArr[index];
            index++;
            if (!str.includes('|')) continue;
            let obj = {}
            str = str.split('|')
            obj.content = str[0].trim()
            obj.time = str[1].trim()
            target.push(obj)
        }
        return target
    }
}

module.exports = new LogController()
